package app.qrcode.browser.ykpixabay.ui.searchpic

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import app.qrcode.browser.ykpixabay.R
import app.qrcode.browser.ykpixabay.logic.model.Hits
import app.qrcode.browser.ykpixabay.ui.star.StarViewModel
import cn.leancloud.LCUser
import kotlinx.android.synthetic.main.fragment_viewpic.*

/**
 * Created by YiGo on 2022/4/17.
 */
class ViewPicFragment : Fragment() {

    val viewModel by lazy { ViewModelProvider(this).get(ViewPicViewModel::class.java) }

    val starViewModel by lazy { ViewModelProvider(this).get(StarViewModel::class.java) }

    private val starList = mutableListOf<Hits>()

    private lateinit var adapter: PicAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_viewpic, container, false)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = PicAdapter(this, viewModel.picList)
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = layoutManager
//        starViewModel.dataListLive.observe(viewLifecycleOwner, Observer {
//            adapter.updateList(it)
//        })
        searchPicEdit.addTextChangedListener {
            val content = it.toString()
            if (content.isNotEmpty()) viewModel.searchPic(content)
            else {
                viewModel.picList.clear()
                adapter.notifyDataSetChanged()
            }
        }
        viewModel.picLiveData.observe(viewLifecycleOwner, Observer { result ->
            val pics = result.getOrNull()
            if (pics != null) {
                viewModel.picList.clear()
                viewModel.picList.addAll(pics)

                starViewModel.updateStar()
                starViewModel.dataListLive.observe(viewLifecycleOwner, Observer { list ->

                    starViewModel.change(list, starList)

                    starList.forEach { star ->
                        pics.forEach {
                            if (it.id == star.id) {
                                it.isStar = true
                            }
                        }
                    }
                    adapter.notifyDataSetChanged()
                })
            } else {
                Toast.makeText(context, "未能查询到任何图片\n请到设置面板检查卡密是否正确或者更换查找关键词", Toast.LENGTH_LONG)
                    .show()
                result.exceptionOrNull()?.printStackTrace()
            }
        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        val controller: NavController = Navigation.findNavController(
            this.requireActivity(),
            R.id.fragmentContainerView
        )
        when (item.itemId) {
            R.id.login_item -> controller.navigate(R.id.action_viewPicFragment_to_loginFragment)
            R.id.settings_not_login_item -> {
                controller.navigate(R.id.action_viewPicFragment_to_settingsNotLoginFragment)
            }
            R.id.account_item -> {
            }
            R.id.star_item -> {
                controller.navigate(R.id.action_viewPicFragment_to_starFragment)
            }
            R.id.settings_login_item -> {
                controller.navigate(R.id.action_viewPicFragment_to_settingsLoginFragment)
            }
        }

        return super.onOptionsItemSelected(item)
    }


    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        if (LCUser.getCurrentUser() == null)
            inflater.inflate(R.menu.menu_not_login, menu)
        else inflater.inflate(R.menu.menu_login, menu)
    }


}